/*-------------------------------------------------------------------------
 *
 * pg_controldata.c
 *
 * 通过一组SQL函数暴露控制数据文件的内容。
 *
 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 * IDENTIFICATION
 *	  src/backend/utils/misc/pg_controldata.c
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

#include "access/htup_details.h"
#include "access/transam.h"
#include "access/xlog.h"
#include "access/xlog_internal.h"
#include "catalog/pg_control.h"
#include "catalog/pg_type.h"
#include "common/controldata_utils.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "storage/lwlock.h"
#include "utils/builtins.h"
#include "utils/pg_lsn.h"
#include "utils/timestamp.h"

Datum pg_control_system(PG_FUNCTION_ARGS)
{
	Datum		fc_values[4];
	bool		fc_nulls[4];
	TupleDesc	fc_tupdesc;
	HeapTuple	fc_htup;
	ControlFileData *fc_ControlFile;
	bool		fc_crc_ok;

	/*
	 * 为结果行构造一个元组描述符。必须与此函数的 pg_proc 条目匹配！
	 */
	fc_tupdesc = CreateTemplateTupleDesc(4);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 1, "pg_control_version",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 2, "catalog_version_no",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 3, "system_identifier",
					   INT8OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 4, "pg_control_last_modified",
					   TIMESTAMPTZOID, -1, 0);
	fc_tupdesc = BlessTupleDesc(fc_tupdesc);

	/* 读取控制文件 */
	LWLockAcquire(ControlFileLock, LW_SHARED);
	fc_ControlFile = get_controlfile(DataDir, &fc_crc_ok);
	LWLockRelease(ControlFileLock);
	if (!fc_crc_ok)
		ereport(ERROR,
				(errmsg("calculated CRC checksum does not match value stored in file")));

	fc_values[0] = Int32GetDatum(fc_ControlFile->pg_control_version);
	fc_nulls[0] = false;

	fc_values[1] = Int32GetDatum(fc_ControlFile->catalog_version_no);
	fc_nulls[1] = false;

	fc_values[2] = Int64GetDatum(fc_ControlFile->system_identifier);
	fc_nulls[2] = false;

	fc_values[3] = TimestampTzGetDatum(time_t_to_timestamptz(fc_ControlFile->time));
	fc_nulls[3] = false;

	fc_htup = heap_form_tuple(fc_tupdesc, fc_values, fc_nulls);

	PG_RETURN_DATUM(HeapTupleGetDatum(fc_htup));
}

Datum pg_control_checkpoint(PG_FUNCTION_ARGS)
{
	Datum		fc_values[18];
	bool		fc_nulls[18];
	TupleDesc	fc_tupdesc;
	HeapTuple	fc_htup;
	ControlFileData *fc_ControlFile;
	XLogSegNo	fc_segno;
	char		fc_xlogfilename[MAXFNAMELEN];
	bool		fc_crc_ok;

	/*
	 * 为结果行构造一个元组描述符。必须与此函数的 pg_proc 条目匹配！
	 */
	fc_tupdesc = CreateTemplateTupleDesc(18);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 1, "checkpoint_lsn",
					   PG_LSNOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 2, "redo_lsn",
					   PG_LSNOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 3, "redo_wal_file",
					   TEXTOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 4, "timeline_id",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 5, "prev_timeline_id",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 6, "full_page_writes",
					   BOOLOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 7, "next_xid",
					   TEXTOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 8, "next_oid",
					   OIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 9, "next_multixact_id",
					   XIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 10, "next_multi_offset",
					   XIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 11, "oldest_xid",
					   XIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 12, "oldest_xid_dbid",
					   OIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 13, "oldest_active_xid",
					   XIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 14, "oldest_multi_xid",
					   XIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 15, "oldest_multi_dbid",
					   OIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 16, "oldest_commit_ts_xid",
					   XIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 17, "newest_commit_ts_xid",
					   XIDOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 18, "checkpoint_time",
					   TIMESTAMPTZOID, -1, 0);
	fc_tupdesc = BlessTupleDesc(fc_tupdesc);

	/* 读取控制文件。 */
	LWLockAcquire(ControlFileLock, LW_SHARED);
	fc_ControlFile = get_controlfile(DataDir, &fc_crc_ok);
	LWLockRelease(ControlFileLock);
	if (!fc_crc_ok)
		ereport(ERROR,
				(errmsg("calculated CRC checksum does not match value stored in file")));

	/*
	 * 计算包含最新检查点的 WAL 文件的 REDO
	 * 起始点的名称。
	 */
	XLByteToSeg(fc_ControlFile->checkPointCopy.redo, fc_segno, wal_segment_size);
	XLogFileName(fc_xlogfilename, fc_ControlFile->checkPointCopy.ThisTimeLineID,
				 fc_segno, wal_segment_size);

	/* 填充值和空数组 */
	fc_values[0] = LSNGetDatum(fc_ControlFile->checkPoint);
	fc_nulls[0] = false;

	fc_values[1] = LSNGetDatum(fc_ControlFile->checkPointCopy.redo);
	fc_nulls[1] = false;

	fc_values[2] = CStringGetTextDatum(fc_xlogfilename);
	fc_nulls[2] = false;

	fc_values[3] = Int32GetDatum(fc_ControlFile->checkPointCopy.ThisTimeLineID);
	fc_nulls[3] = false;

	fc_values[4] = Int32GetDatum(fc_ControlFile->checkPointCopy.PrevTimeLineID);
	fc_nulls[4] = false;

	fc_values[5] = BoolGetDatum(fc_ControlFile->checkPointCopy.fullPageWrites);
	fc_nulls[5] = false;

	fc_values[6] = CStringGetTextDatum(psprintf("%u:%u",
											 EpochFromFullTransactionId(fc_ControlFile->checkPointCopy.nextXid),
											 XidFromFullTransactionId(fc_ControlFile->checkPointCopy.nextXid)));
	fc_nulls[6] = false;

	fc_values[7] = ObjectIdGetDatum(fc_ControlFile->checkPointCopy.nextOid);
	fc_nulls[7] = false;

	fc_values[8] = TransactionIdGetDatum(fc_ControlFile->checkPointCopy.nextMulti);
	fc_nulls[8] = false;

	fc_values[9] = TransactionIdGetDatum(fc_ControlFile->checkPointCopy.nextMultiOffset);
	fc_nulls[9] = false;

	fc_values[10] = TransactionIdGetDatum(fc_ControlFile->checkPointCopy.oldestXid);
	fc_nulls[10] = false;

	fc_values[11] = ObjectIdGetDatum(fc_ControlFile->checkPointCopy.oldestXidDB);
	fc_nulls[11] = false;

	fc_values[12] = TransactionIdGetDatum(fc_ControlFile->checkPointCopy.oldestActiveXid);
	fc_nulls[12] = false;

	fc_values[13] = TransactionIdGetDatum(fc_ControlFile->checkPointCopy.oldestMulti);
	fc_nulls[13] = false;

	fc_values[14] = ObjectIdGetDatum(fc_ControlFile->checkPointCopy.oldestMultiDB);
	fc_nulls[14] = false;

	fc_values[15] = TransactionIdGetDatum(fc_ControlFile->checkPointCopy.oldestCommitTsXid);
	fc_nulls[15] = false;

	fc_values[16] = TransactionIdGetDatum(fc_ControlFile->checkPointCopy.newestCommitTsXid);
	fc_nulls[16] = false;

	fc_values[17] = TimestampTzGetDatum(time_t_to_timestamptz(fc_ControlFile->checkPointCopy.time));
	fc_nulls[17] = false;

	fc_htup = heap_form_tuple(fc_tupdesc, fc_values, fc_nulls);

	PG_RETURN_DATUM(HeapTupleGetDatum(fc_htup));
}

Datum pg_control_recovery(PG_FUNCTION_ARGS)
{
	Datum		fc_values[5];
	bool		fc_nulls[5];
	TupleDesc	fc_tupdesc;
	HeapTuple	fc_htup;
	ControlFileData *fc_ControlFile;
	bool		fc_crc_ok;

	/*
	 * 为结果行构造一个元组描述符。必须与此函数的 pg_proc 条目匹配！
	 */
	fc_tupdesc = CreateTemplateTupleDesc(5);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 1, "min_recovery_end_lsn",
					   PG_LSNOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 2, "min_recovery_end_timeline",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 3, "backup_start_lsn",
					   PG_LSNOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 4, "backup_end_lsn",
					   PG_LSNOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 5, "end_of_backup_record_required",
					   BOOLOID, -1, 0);
	fc_tupdesc = BlessTupleDesc(fc_tupdesc);

	/* 读取控制文件 */
	LWLockAcquire(ControlFileLock, LW_SHARED);
	fc_ControlFile = get_controlfile(DataDir, &fc_crc_ok);
	LWLockRelease(ControlFileLock);
	if (!fc_crc_ok)
		ereport(ERROR,
				(errmsg("calculated CRC checksum does not match value stored in file")));

	fc_values[0] = LSNGetDatum(fc_ControlFile->minRecoveryPoint);
	fc_nulls[0] = false;

	fc_values[1] = Int32GetDatum(fc_ControlFile->minRecoveryPointTLI);
	fc_nulls[1] = false;

	fc_values[2] = LSNGetDatum(fc_ControlFile->backupStartPoint);
	fc_nulls[2] = false;

	fc_values[3] = LSNGetDatum(fc_ControlFile->backupEndPoint);
	fc_nulls[3] = false;

	fc_values[4] = BoolGetDatum(fc_ControlFile->backupEndRequired);
	fc_nulls[4] = false;

	fc_htup = heap_form_tuple(fc_tupdesc, fc_values, fc_nulls);

	PG_RETURN_DATUM(HeapTupleGetDatum(fc_htup));
}

Datum pg_control_init(PG_FUNCTION_ARGS)
{
	Datum		fc_values[11];
	bool		fc_nulls[11];
	TupleDesc	fc_tupdesc;
	HeapTuple	fc_htup;
	ControlFileData *fc_ControlFile;
	bool		fc_crc_ok;

	/*
	 * 为结果行构造一个元组描述符。必须与此函数的 pg_proc 条目匹配！
	 */
	fc_tupdesc = CreateTemplateTupleDesc(11);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 1, "max_data_alignment",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 2, "database_block_size",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 3, "blocks_per_segment",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 4, "wal_block_size",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 5, "bytes_per_wal_segment",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 6, "max_identifier_length",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 7, "max_index_columns",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 8, "max_toast_chunk_size",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 9, "large_object_chunk_size",
					   INT4OID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 10, "float8_pass_by_value",
					   BOOLOID, -1, 0);
	TupleDescInitEntry(fc_tupdesc, (AttrNumber) 11, "data_page_checksum_version",
					   INT4OID, -1, 0);
	fc_tupdesc = BlessTupleDesc(fc_tupdesc);

	/* 读取控制文件 */
	LWLockAcquire(ControlFileLock, LW_SHARED);
	fc_ControlFile = get_controlfile(DataDir, &fc_crc_ok);
	LWLockRelease(ControlFileLock);
	if (!fc_crc_ok)
		ereport(ERROR,
				(errmsg("calculated CRC checksum does not match value stored in file")));

	fc_values[0] = Int32GetDatum(fc_ControlFile->maxAlign);
	fc_nulls[0] = false;

	fc_values[1] = Int32GetDatum(fc_ControlFile->blcksz);
	fc_nulls[1] = false;

	fc_values[2] = Int32GetDatum(fc_ControlFile->relseg_size);
	fc_nulls[2] = false;

	fc_values[3] = Int32GetDatum(fc_ControlFile->xlog_blcksz);
	fc_nulls[3] = false;

	fc_values[4] = Int32GetDatum(fc_ControlFile->xlog_seg_size);
	fc_nulls[4] = false;

	fc_values[5] = Int32GetDatum(fc_ControlFile->nameDataLen);
	fc_nulls[5] = false;

	fc_values[6] = Int32GetDatum(fc_ControlFile->indexMaxKeys);
	fc_nulls[6] = false;

	fc_values[7] = Int32GetDatum(fc_ControlFile->toast_max_chunk_size);
	fc_nulls[7] = false;

	fc_values[8] = Int32GetDatum(fc_ControlFile->loblksize);
	fc_nulls[8] = false;

	fc_values[9] = BoolGetDatum(fc_ControlFile->float8ByVal);
	fc_nulls[9] = false;

	fc_values[10] = Int32GetDatum(fc_ControlFile->data_checksum_version);
	fc_nulls[10] = false;

	fc_htup = heap_form_tuple(fc_tupdesc, fc_values, fc_nulls);

	PG_RETURN_DATUM(HeapTupleGetDatum(fc_htup));
}
